﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using MASAS.MSM.DomainLayer.Filtering;
using MASAS.MSM.DomainLayer.Model;

namespace MASAS.MSM.DomainLayer.Feed
{

    /// <summary>
    /// Enries available event.
    /// </summary>
    /// <param name="sender">The sender.</param>
    /// <param name="hub">The hub.</param>
    /// <param name="entries">The entries.</param>
    public delegate void EntriesAvailableEvent( object sender, Hub hub, List<HubEntry> entries );

    /// <summary>
    /// Feed Poller class.
    /// </summary>
    public class FeedPoller
    {

        // Private members...
        private HubFacade       _hubFacade;
        private FilterManager   _filterMgr;

        /// <summary>
        /// Occurs when [on new entries available].
        /// </summary>
        public event EntriesAvailableEvent OnNewEntriesAvailable;

        /// <summary>
        /// Initializes a new instance of the <see cref="FeedPoller"/> class.
        /// </summary>
        /// <param name="hubFacade">The hub facade.</param>
        public FeedPoller( HubFacade hubFacade )
        {
            this._hubFacade = hubFacade;

            _filterMgr = new FilterManager();
        }

        /// <summary>
        /// Checks the feed.
        /// </summary>
        /// <param name="data">The data.</param>
        public void CheckFeed( List<Hub> hubs )
        {
            foreach( Hub hub in hubs )
            {
                string hubDetails = string.Format( "Retrieving items from hub {0}: URL({1}), Access({2})", hub.Name, hub.URI, hub.Access );
                Logging.Logger.AddLogEntry( hubDetails );

                if( (hub.Access & Hub.AccessType.Read ) == Hub.AccessType.Read )
                {
                    // Get the entries...
                    List<HubEntry> retrievedEntries = _hubFacade.GetEntries( hub );

                    // Apply the filters to the entries...
                    _filterMgr.ApplyFilters( hub.Filters, retrievedEntries );

                    // Notify the entries have been processed...
                    OnNewEntriesAvailable( this, hub, retrievedEntries );
                }
            }
            Logging.Logger.AddLogEntry( "Done!" );
        }
        
    }

}